package com.huizhonglm.diap.ui.shop;

import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.model.shop.ShopDetailResponse;
import com.huizhonglm.diap.api.model.shop.ShowImg;
import com.huizhonglm.diap.core.image.Thumb;
import com.huizhonglm.diap.core.utils.DisplayUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.presenters.shop.ShopDetailPresenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.shop.iView.ShopDetailIView;
import com.huizhonglm.diap.widget.Banner;
import com.huizhonglm.diap.widget.LoadView;
import com.huizhonglm.diap.widget.xGallery.XGalleryView;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-16 10:51
 */
public class ShopDetailActivity extends BaseActivity implements ShopDetailIView, View.OnClickListener,
        LoadView.OnLoadAgainListener {

    private LayoutInflater mInflater;

    private ImageButton collectIbtn;
    private LoadView loadView;
    private Banner shopBanner;
    private TextView shopNameTxt;
    private TextView discountInfoTxt;
    private TextView pointRuleTxt;
    private WebView descriptionWeb;

    private ShopDetailPresenter mPresenter;

    private ShopDetailResponse shopDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        setBackEvent(this, null);
        mInflater = getLayoutInflater();
        mPresenter = new ShopDetailPresenter(this);
        assignViews();
    }

    @Override
    protected void assignViews() {
        collectIbtn = (ImageButton) findViewById(R.id.title_collect_ibtn);
        View dataView = findViewById(R.id.shop_detail_scrl);
        loadView = (LoadView) findViewById(R.id.load_view);
        shopBanner = (Banner) findViewById(R.id.shop_banner);
        shopNameTxt = (TextView) findViewById(R.id.shop_name_txt);
        discountInfoTxt = (TextView) findViewById(R.id.discount_info_txt);
        pointRuleTxt = (TextView) findViewById(R.id.point_role_txt);
        descriptionWeb = (WebView) findViewById(R.id.description_web);

        // 初始化图片高度
        float screenWidth = DisplayUtil.getWidth();
        float bannerHeight = screenWidth * 100f / 160f;
        shopBanner.onCreateView();
        shopBanner.setBannerSize(screenWidth, bannerHeight);

        // 初始化webView
        descriptionWeb.setWebChromeClient(mWebChromeClient);
//        initWebSettings();

        loadView.setDataView(dataView, this);
        collectIbtn.setOnClickListener(this);
    }

    private void initBanner(){
        final List<String> data = new ArrayList<>();
        data.add(shopDetail.getPicPath());
        String imgJson = shopDetail.getJsonImgs();
        if (!EmptyUtil.isEmpty(imgJson)) {
            List<ShowImg> imgs = JSON.parseArray(imgJson, ShowImg.class);
            if (!EmptyUtil.isEmpty(imgs)) {
                for (ShowImg img: imgs) {
                    data.add(img.getShowImg());
                }
            }
        }
        List<ImageView> views = new ArrayList<>();
        // 将最后一个ImageView添加进来
        views.add(getBannerImage(data.get(data.size() - 1)));
        for (int i = 0; i < data.size(); i++) {
            views.add(getBannerImage(data.get(i)));
        }
        // 将第一个ImageView添加进来
        views.add(getBannerImage(data.get(0)));
        // 设置循环，在调用setData方法前调用
        shopBanner.setCycle(true);
        // 在加载数据前设置是否循环
        shopBanner.setData(views, new Banner.OnBannerClickListener() {

            @Override
            public void onBannerClick(int position, View imageView) {
                if (shopBanner.isCycle()) {
                    XGalleryView xGallery = new XGalleryView(ShopDetailActivity.this);
                    xGallery.show(imageView, data, position);
                }
            }
        });
        //设置轮播
        if (data.size() > 1){
            shopBanner.setWheel(true);
            shopBanner.setTime(7000);
        } else {
            shopBanner.setWheel(false);
        }
        //设置圆点指示图标组居中显示，默认靠右
        shopBanner.setIndicatorCenter();
    }

    private ImageView getBannerImage(String imgUrl) {
        ImageView image = (ImageView)mInflater.inflate(R.layout.item_banner_image, null);
        image.setTag(imgUrl);
        Thumb.getInstance().display(image, imgUrl, R.drawable.def_banner);
        return image;
    }

    /**
     * 设置WebView属性
     */
//    private void initWebSettings() {
//        WebSettings settings = descriptionWeb.getSettings();
//        descriptionWeb.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
//        // 设置字符集编码
//        String encodingName = settings.getDefaultTextEncodingName();
//        if (!"AUTOSELECT".equals(encodingName)) {
//            settings.setDefaultTextEncodingName("UTF-8");
//        }
//        settings.setSupportZoom(false);
//        settings.setBuiltInZoomControls(false);
//        settings.setUseWideViewPort(true);// 这个很关键
//        settings.setLoadWithOverviewMode(true);
//        /**
//         * 用WebView显示图片，可使用这个参数 设置网页布局类型： 1、LayoutAlgorithm.NARROW_COLUMNS ：
//         * 适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
//         */
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        descriptionWeb.requestFocus();
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_collect_ibtn:
                showProgressBar();
                if ("Y".equals(shopDetail.getIsCollected())) {
                    mPresenter.cancelCollect(shopDetail.getSid());
                } else {
                    mPresenter.collectShop(shopDetail.getSid());
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        onLoadAgain();
    }

    @Override
    public void onLoadAgain() {
        String shopId = getIntent().getStringExtra("shopId");
        mPresenter.loadDetail(shopId);
    }

    @Override
    public void onLoadDetailSuccess(ShopDetailResponse resp) {
        if (resp != null) {
            shopDetail = resp;
            setDetailValue();
        } else {
            loadView.showErrorView();
        }
    }

    @Override
    public void onLoadDetailFailure() {
        loadView.showErrorView();
    }

    @Override
    public void onCollectSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("收藏成功");
        shopDetail.setIsCollected("Y");
        toggleCollectStatus();
    }

    @Override
    public void onCollectFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("收藏失败，请稍后重试");
    }

    @Override
    public void onCancelSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("取消收藏成功");
        shopDetail.setIsCollected("N");
        toggleCollectStatus();
    }

    @Override
    public void onCancelFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("取消收藏失败，请稍后重试");
    }

    private void toggleCollectStatus(){
        if (UserUtil.isLogin()) {
            collectIbtn.setVisibility(View.VISIBLE);
            if ("Y".equals(shopDetail.getIsCollected())) {
                collectIbtn.setImageResource(R.drawable.title_btn_collect_s);
            } else {
                collectIbtn.setImageResource(R.drawable.title_btn_collect_n);
            }
        } else {
            collectIbtn.setVisibility(View.GONE);
        }
    }

    private void setDetailValue(){
        toggleCollectStatus();
        initBanner();
        shopNameTxt.setText("店铺名称：" + shopDetail.getSpName());
        if (!EmptyUtil.isEmpty(shopDetail.getDiscountInfo())) {
            discountInfoTxt.setText("商铺介绍：" + Html.fromHtml(shopDetail.getDiscountInfo()));
        } else {
            discountInfoTxt.setText("商铺介绍：");
        }
        if (!EmptyUtil.isEmpty(shopDetail.getPointRole())) {
            pointRuleTxt.setText("消费提示：" + Html.fromHtml(shopDetail.getPointRole()));
        } else {
            pointRuleTxt.setText("消费提示：");
        }
        loadDescWeb(shopDetail.getDescription());
    }

    private void loadDescWeb(String descHtml){
        descriptionWeb.clearCache(true);
        descriptionWeb.clearHistory();
        descriptionWeb.clearFormData();
        descriptionWeb.loadDataWithBaseURL(null, descHtml, "text/html", "utf-8", null);
    }

    public final WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress >= 100) {
                loadView.showDataView();
            }
        }
    };
}
